package edu.unc.lensblaster.flickr;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.uploader.UploadMetaData;
import com.aetrion.flickr.uploader.Uploader;

public class Main extends Activity {
	
	private static int ACTIVITY_AUTH = 0;
	private static final String PREFERENCES = "lensblaster";
	
	private String frob = null;
	private AuthInterface ai = null;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //  Clear stored token and cookies -- For testing purposes ONLY!
        CookieSyncManager.createInstance(this);
        CookieManager cm = CookieManager.getInstance();
        cm.removeAllCookie();
        SharedPreferences sp = getSharedPreferences(PREFERENCES,0);
        Editor ed =  sp.edit();
        ed.clear();
        ed.commit();
        //////////////////////////////////////////////////////////
        
        // Set up ViewGroup
        LinearLayout vg = new LinearLayout(this);
        vg.setOrientation(LinearLayout.VERTICAL);
        vg.setBackgroundColor(android.graphics.Color.YELLOW);
        
        // Set up text
        final TextView tv = new TextView(this);
        tv.setText("Click to upload picture");
        tv.setTextColor(android.graphics.Color.BLACK);
        
        // Set up button
        Button b = new Button(this);
        b.setText("UPLOADz!");
        b.setOnClickListener(new View.OnClickListener(){
        	public void onClick(View v){
        		upload();
        		tv.setText("Photo uploaded (not really)");
        	}
        });
  
        vg.addView(tv);
        vg.addView(b);
        setContentView(vg);
    }
    
    public void upload(){
    	try{
    		
    		SharedPreferences sp = getSharedPreferences(PREFERENCES, 0);
    	
			String apiKey = "8a6d79ea850cda7c1145a631260c150b";
			String sSecret = "16937549996b3a1e";
			
			// Arbitrarily return a junk default value of "-1" if token is not present
			String token = sp.getString("token","-1");//"72157607488314332-404db2b373db1bc2";
			android.util.Log.d("lens","token from preferences = " + token);
		
			// Set up Flickr objects
			Uploader uploader = new Uploader(apiKey,sSecret);
			REST rest = new REST();
			RequestContext requestContext = RequestContext.getRequestContext();
			//AuthInterface ai = new AuthInterface(apiKey,sSecret,rest);//flickr.getAuthInterface();	//
			ai = new AuthInterface(apiKey,sSecret,rest);
			
			// Validate token, retrieve new one if necessary and store to file
			Auth validToken;
			
			try{
				validToken = ai.checkToken(token);
			}catch(FlickrException e){
				getNewToken();		// Launch web-auth sequence, wait for result
				return;
			}
			
			
			// Prepare for upload
			requestContext.setAuth(validToken);
			UploadMetaData umd = new UploadMetaData();
			umd.setTitle("Test");
			FileInputStream is = new FileInputStream(new File("/sdcard/dcim/Camera/derp.jpg"));
			BufferedInputStream in = new BufferedInputStream(is);
			
			// Upload
			android.util.Log.d("lens", "Uploading file");
			String photoId = uploader.upload(in,umd);
			android.util.Log.d("lens", "Finished uploading");
			in.close();
			is.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
    
    public void getNewToken(){
    	android.util.Log.d("lens", "Retrieving new token");
    	
    	// Request frob
    	try{
    		frob = ai.getFrob();
    	}catch (Exception e){
    		e.printStackTrace();
    	}
    	
    	//Build authentication url
    	URL authURL = null;
    	try{
    	authURL = ai.buildAuthenticationUrl(Permission.WRITE, frob);
    	}catch(MalformedURLException e){
    		e.printStackTrace();
    	}
    	
    	android.util.Log.d("lens", "Auth URL = " + authURL.toString());
		try{
			Intent i = new Intent(this, WebAuthentication.class);
			i.putExtra(android.app.SearchManager.QUERY, authURL.toString());
			startActivityForResult(i, ACTIVITY_AUTH);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, 
                                    Intent intent) {
    	android.util.Log.d("lens","returned to main activity");
        super.onActivityResult(requestCode, resultCode, intent);

        Auth token = null;
		try{
			token = ai.getToken(frob);
		}catch (Exception e){
			android.util.Log.e("lens", "error retrieving token");
			e.printStackTrace();
		}
		
		SharedPreferences sp = getSharedPreferences(PREFERENCES, 0);
        Editor e = sp.edit();
        e.putString("token",token.getToken());
        e.commit();
        upload();			// Try uploading again
    }
}